package sholmes.euler.problem8;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;

/**
 * Find the greatest product of five consecutive digits in the 1000-digit
 * number. Solution runtime O(2n) -> O(n)
 * 
 * @author Justin A. McCoy {mailto:justinmccoy@acm.org}
 * 
 */
public class Problem8 {

	static final String largeNumberFile = "largeNumber.dat";

	public static void main(String[] args) {
		ArrayList<Integer> numberArray = new ArrayList<Integer>();

		try {
			readInputFile(largeNumberFile, numberArray);
		} catch (IOException e) {
			System.err.println("Error reading from file: " + largeNumberFile);
		}
		System.out.println("Largest Product of 5 consecutive numbers found in file [" + largeNumberFile + "] is: "
				+ findLargestProduct(numberArray));
		return;
	}

	/**
	 * Returns the largest product of consecutive 5 numbers within a larger number stored in 
	 * aNumberArray 
	 * 
	 * Runtime O(n) run through each of the digits in the large number once.
	 * 
	 * @param aNumberArray - A Large Number stored in a list
	 * @return the largest product of 5 consecutive numbers found in the passed parameter
	 */
	private static int findLargestProduct(ArrayList<Integer> aNumberArray) {
		int largestProduct = -1; // Start with an initial value that is less
									// then any potential value

		// Magic number 4 is one less then the number that we are finding the
		// product of digits for.
		for (int inc = 0; inc + 4 < aNumberArray.size(); inc++) {
			largestProduct = Math.max(
					aNumberArray.get(inc) * aNumberArray.get(inc + 1)
							* aNumberArray.get(inc + 2)
							* aNumberArray.get(inc + 3)
							* aNumberArray.get(inc + 4), largestProduct);
		}
		return largestProduct;
	}

	/**
	 * Read a file containing a large number into an ArrayList
	 * 
	 * Runtime O(n) - cycles through the entire number adding each digit to the
	 * arraylist.
	 * 
	 * @param aLargeNumberFile - file containing a large number
	 * @param aNumberArray - ArrayList that the number is read into 
	 * @throws IOException
	 */
	private static void readInputFile(String aLargeNumberFile,
			Collection<Integer> aNumberArray) throws IOException {
		File file = new File(aLargeNumberFile);
		if (!file.exists()) {
			System.out.println(aLargeNumberFile + " does not exist.");
			return;
		}
		if (!(file.isFile() && file.canRead())) {
			System.out.println(file.getName() + " cannot be read from.");
			return;
		}

		FileInputStream fis = new FileInputStream(file);
		char current;

		while (fis.available() > 0) {
			current = (char) fis.read();
			aNumberArray.add(Character.getNumericValue(current));
		}
		
	}

}
